package chpt05.shopping.dao;
import java.util.ArrayList;
import java.util.List;

import chpt05.shopping.Commodity;

public class CommodityDAOArrayImpl implements CommodityDAO {
    private Commodity[] commodities;
    private int size; // 商品数量

    public CommodityDAOArrayImpl(int capacity) {
        commodities = new Commodity[capacity];
        size = 0;
    }

    @Override
    public void init() {
        // 初始化商品数组
        commodities = new Commodity[commodities.length];
        size = 0;
        List<Commodity> datas = CommodityDataGenerator.generateData();
        for (Commodity commodity : datas) {
			this.add(commodity);
		}
    }

    @Override
    public List<Commodity> findAll() {
        // 显示所有商品
        List<Commodity> result = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            result.add(commodities[i]);
        }
        return result;
    }

    @Override
    public boolean add(Commodity commodity) {
        // 检查是否存在相同 ID 的商品
        for (int i = 0; i < size; i++) {
            if (commodities[i].getId().equals(commodity.getId())) {
                return false; // ID 相同的商品已存在，添加失败
            }
        }

        // 添加商品
        if (size < commodities.length) {
            commodities[size] = commodity;
            size++;
            return true; // 添加成功
        }
        return false; // 数组已满，添加失败
    }

    @Override
    public List<Commodity> findByName(String name) {
        // 根据名称查找商品列表
        List<Commodity> result = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            if (commodities[i].getName().contains(name)) {
                result.add(commodities[i]);
            }
        }
        return result;
    }

    @Override
    public Commodity findById(Integer id) {
        // 根据id查找商品
        for (int i = 0; i < size; i++) {
            if (commodities[i].getId().equals(id)) {
                return commodities[i];
            }
        }
        return null;
    }

}